/*
 * @Author: sundeqi
 * @Date: 2022-03-29 11:34:31
 * @LastEditors: sundeqi
 * @LastEditTime: 2022-03-30 18:32:40
 * @Description: 基类
 */
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:gkb_webview/gkb_webview.dart';

class LiveStreamController {
  factory LiveStreamController() => _getInstance();

  static LiveStreamController? _instance;

  LiveStreamController._();

  static LiveStreamController _getInstance() {
    _instance ??= LiveStreamController._();
    return _instance!;
  }

  final InAppLocalhostServer _localServer = InAppLocalhostServer();

  void start() async {
    // start the localhost server
    await _localServer.start();

    if (Platform.isAndroid) {
      await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
    }
  }

  void stop() {
    _localServer.close();
  }
}

abstract class BaseWidget extends StatefulWidget {
  final String url;
  final String bgImgUrl;
  const BaseWidget({Key? key, required this.url, this.bgImgUrl = ''})
      : super(key: key);
}

abstract class BaseWidgetState<T extends BaseWidget> extends State<T>
    with WebViewDelegate {
  @protected
  HtmlController? webControl;

  @override
  void onWebViewCreated(HtmlController controller) {
    webControl = controller;
  }

  @override
  void onPageFinished(String src) {
    webControl?.evalRawJavascript('''
      var bgDiv = document.getElementsByClassName('upcoming-bg')[0];
			bgDiv.style.backgroundImage = 'url(' + ${widget.bgImgUrl} + ')';
    ''');
    webControl?.evalRawJavascript('loadSrc(\'${widget.url})\'');
  }

  String get htmlPath;

  @override
  Widget build(BuildContext context) {
    //'http://localhost:8080'
    return GKBWebview(
      url: htmlPath,
      delegate: this,
    );
  }
}
